#include "../server.hpp"


uint64_t conn_id = 0;

std::unordered_map<uint64_t, PtrConnection> _conns;
void ConnectionDestroy(const PtrConnection &conn)
{
    _conns.erase(conn->Id());
}
void OnConnected(const PtrConnection &conn)
{
    DEBUG_LOG("New Connection: %p", conn.get());
}
void OnMessage(const PtrConnection &conn, Buffer *buf)
{
    std::string bufstr = buf->ReadAsString(buf->ReadableSize()).c_str();
    DEBUG_LOG("%s", bufstr.c_str());
    buf->ReadMove(buf->ReadableSize());
    std::string echostr = "Server echo: " + bufstr;
    conn->Send(&echostr[0], echostr.size());
    // conn->ShutDown();
}

EventLoop base_loop;
LoopThreadPool *_thread_pool;

void NewConnection(int fd)
{
    conn_id++;

    PtrConnection conn(new Connection(_thread_pool->NextLoop(), conn_id, fd));   
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));  
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));

    conn->EnableInactiveRelease(10);
    conn->Connected();  // 就绪初始化


    _conns.insert(std::make_pair(conn_id, conn));
    DEBUG_LOG("NEW Thread has been Create...");
}

void t1()
{
    _thread_pool = new LoopThreadPool(&base_loop);
    _thread_pool->SetThreadCount(2);
    _thread_pool->Create();

    // Poller poller;
    Acceptor acceptor(&base_loop, 8765);

    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));       // 设置监听套接字的可读监控，这里回调函数需要为 新连接创建 Channel 并添加监控
    acceptor.Listen();  // 启动可读事件监控


    
    base_loop.Start();
    

}


int main()
{
    t1();

    return 0;
}